<template>
<view class="main-view">
	<view v-if="errmsg==''" class="content-view">
		<scroll-view scroll-y="true" style="height: calc(100vh - 42px);">
		<block  :key="index" v-for="(item, index) in datalist">
			<view  @click="selectitem(index)"  :style="{ right: item.right + 'rpx'}"  style="margin: 10px 5px 0 5px;padding:0 10px; background-color: #fff;display: flex;position: relative;"  class="order-item" :data-index="index">
				<view style="display: flex;flex-direction: column;width: calc(100vw - 30px); ">
					<view  v-for="(item1, index1) in item.data" :key="index1" style="width: calc(100vw - 30px);">
					   <view v-if="item1.style.colVisible && item1.style.editStyle != 'checkbox'" style="color: #666;font-size: 14px; display: flex;flex-direction: row;align-items: center;padding: 5px 0;">
						   <view >{{item1.style.colText}}:</view>
							<view style="border-radius: 5px;padding: 2px 5px;">{{item1.style.value}}</view>
					   </view>
					   <view v-if="index1!=(item.content.length-1) && item1.style.colVisible" style="height: 1px;width: 100%;background-color: #f0f0f0;"></view>
				   </view>
				</view>
				<view style="position: absolute;right: 20px;top:10px;" >
					<view class="iconfont icon-xuanzhongduigou" :style="{color:item.data[selectedindex].style.value==1?'#f00':'#aaa'}" style="font-size: 28px;"  ></view>
				</view>
			</view>
		</block>
		</scroll-view>	
		<view class="bottom-wrapper" >
			<view  style="display: flex;height: 100%;margin-bottom: 10px;justify-content: center;">
				<view @click="btnclick(0)"  style="margin-left: 5vw; width: 90vw; border-radius: 10px; align-items: center; display: flex;justify-content: center;height: 100%; background-color: #F55C23;color: #fff;">{{btns[0].text}}</view>
			</view>
		</view>
	</view>
	<view v-else class="error-view">
		{{errmsg}}
	</view>
</view>
</template>

<script>
var util = require("../../utils/util.js");
var infolistutil = require("../../utils/infolistutil.js");
import LyTree from '@/components/ly-tree/ly-tree.vue'
const app = getApp().globalData;
export default{
	
	components: {
		LyTree
	},
	data() {
		return {
			btns:[{"name": "save","text": "保存","type": "save","visible": true,"btnToDo": "save","clicked": {},"position": "pagebottom"}],
			errmsg:'',
			datalist:[],
			olddatalist:[],
			divlist:{},
			datasave:[],
			olddatasave:[],
			divsave:{},
			setnames:[],
			oldsetnames:[],
			divsetname:{},
			pageName:'',
			templetName:'',
			modid:'',
			menuid:'',
			layercontent:{},
			conditions:{},
			conditionsname:'',
			div:[],
			datastyle:[],
			rowClickDynamic:{},
			rowClick:'',
			isloadmore:true,
			dataObject:'',
			divArea:'',
			colNames:[],
			isrequest:true,
			selectedindex:0,
			keyColumn:'',
			nameColumn: '',
			namesColumn: ''
		}
	},
	
	onLoad:function(options){
		var that = this
		console.log(options)
		uni.hideHomeButton()
		var productCode = uni.getStorageSync('productCode')
		var sessionId = uni.getStorageSync('sessionId')
		var projectCode = uni.getStorageSync('projectCode')
		var terminaltype = uni.getStorageSync('terminaltype')
		var dbId = uni.getStorageSync('dbId')
		var userId = uni.getStorageSync('userId')
		var userName = uni.getStorageSync('userName')
		var pageName = options.pagename
		var templetName = options.templatename
		var modid = options.modid
		var menuid = options.menuid
		var conditions = options.conditions==undefined ? {} : JSON.parse(options.conditions)
		that.conditions = conditions
		that.pageName = pageName
		that.templetName = templetName
		that.modid = modid
		that.menuid  = menuid
		uni.setNavigationBarTitle({title:options.menuname})
		var injson = '{"productCode":"' + productCode + '","terminalType":"' + terminaltype + '","projectCode":"' +
			projectCode + '","dbId":"' + dbId + '","templetName":"' + templetName + '","pageName":"' + pageName +
			'","menuId":"'+menuid+'","modId":"' + modid + '","sessionId":"' + sessionId + '","userId":"' + userId +
			'","userName":"' + userName + '"}';
		console.log(injson)
		uni.showLoading({
			title: '加载中'
		})
		uni.request({
			url: getApp().globalData.app_address + '?method=saas_PageStyle&parse=json',
			data: injson,
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			success: function(res) {
				var result = res.data;
				console.log(result)
				that.keyColumn= result.data.page.keyColumn
				that.nameColumn= result.data.page.nameColumn
				that.namesColumn= result.data.page.namesColumn
				var div = result.data.div
				that.div = div
				uni.hideLoading()
				div.forEach(function(val,index){
					var datastyle = val.style.colStyle
					var divArea = val.divArea
					if(divArea == 'dw_datalist'){
						that.divlist = val
					}else if(divArea == 'dw_datasave'){
						that.divsave = val
					}else if(divArea == 'dw_setnames'){
						that.divsetname = val
					}
					var dataObject = val.style.dataObject
					that.dataObject = dataObject
					var pageConditions = {}
					pageConditions['pageNumber'] = 1
					pageConditions['rowsPerPage'] = 20
					pageConditions['isAllData'] = false
					that.pageConditions = pageConditions
					var temconditions = {}
					if(val.style.conditions != undefined){
						temconditions[divArea] = conditions
						that.conditions = temconditions
					}
					var replaceConditions = {}
					var replaceColumns = val.style.replaceColumns
					if(JSON.stringify(replaceColumns) != '[]' && replaceColumns != undefined){
						for(var q=0; q<replaceColumns.length; q++){
							var type = replaceColumns[q].type
							if(type == 'column'){
								var colName= replaceColumns[q].column.colName
								replaceConditions[replaceColumns[q].toReplace] = conditions[colName]
							}
							if(type == 'value'){
								var replaceValue = replaceColumns[q].value
								if(replaceValue == "#PROJECTCODE#"){
									replaceConditions[replaceColumns[q].toReplace] = uni.getStorageSync('projectCode')
								}
							}
						}
					}
					var injson2 = '{"productCode":"' + productCode + '","terminalType":"' + terminaltype + '","projectCode":"' +
						projectCode + '","dbId":"' + dbId + '","templetName":"' + templetName + '","pageName":"' + pageName +
						'","menuId":"'+menuid+'","modId":"' + modid + '","sessionId":"' + sessionId + '","userId":"' + userId +
						'","userName":"' + userName + '","divArea":"' + divArea + '","dataObject":"' + dataObject + 
						'","conditions":' + JSON.stringify(temconditions) + ',"replaceConditions":' + JSON.stringify(replaceConditions) + ',"pageConditions":' + JSON.stringify(that.pageConditions) + '}';
					console.log('injson2' + injson2)
					var url = getApp().globalData.app_address + '?method=saas_PageDivData&parse=json'
					that.$options.methods.getdatalist(url, injson2,datastyle,divArea,that)
				})
				
			},
		})
	},
	 
	methods: {
		
		async getdatalist(url, injson2,datastyle,divarea,that){
			const { data: res } = await infolistutil.post2(url, injson2);
			var result = res.data;
			console.log(res)
			var datalisttemp = res.data.div.value
			var datalist = []
			for(var k=0; k<datalisttemp.length; k++){
				var obj = {}
				obj['opttype'] = ''
				for(var m=0; m<datastyle.length; m++){
					datastyle[m].style['value'] = datalisttemp[k][datastyle[m].name]
					datastyle[m].style['colValue'] = datalisttemp[k][datastyle[m].name]
					datastyle[m].style['coldisplay'] = datalisttemp[k][datastyle[m].name]
				}
				obj['data'] = JSON.parse(JSON.stringify(datastyle))
				datalist.push(obj)
			}
			if(divarea == 'dw_datalist'){
				that.datalist = datalist
				var dataitem = datalist[0].data
				dataitem.forEach(function(val,index){
					if(val.style.editStyle === 'checkbox'){
						that.selectedindex = index
						console.log(that.selectedindex)
					}
				})
				that.olddatalist = JSON.parse(JSON.stringify(datalist))
			}else if(divarea == 'dw_datasave'){
				that.datasave = datalist
				that.olddatasave = JSON.parse(JSON.stringify(datalist))
				console.log(that.datasave)
			}else if(divarea == 'dw_setnames'){
				that.setnames = datalist
				that.oldsetnames = JSON.parse(JSON.stringify(datalist))
			}
			
		},
		
		selectitem(index){
			var that = this
			var datalist = that.datalist
			var item = datalist[index].data
			var itemvalue = item[that.selectedindex].style.value
			if(itemvalue == 0){
				itemvalue = 1
				var divsave = that.divsave.style
				var conditions = that.conditions
				var initialValues = divsave.initialValues
				var temobj = {}
				if(JSON.stringify(initialValues) !='[]' && JSON.stringify(conditions) != '{}' ){
					let condition
					for(condition in conditions){
						for(var n=0; n<initialValues.length; n++){
							var foreignKeyArr = initialValues[n].foreignKeyArr
							for(var o=0; o<foreignKeyArr.length; o++){
								if(condition == foreignKeyArr[o].baseKey){
									temobj[condition] = conditions[condition]
								}
							}
						}
					}
				}
				let maparr = item.filter((val, index)=>{
					 return val.name == that.keyColumn
				})
				temobj[that.keyColumn] = maparr[0].style.value
				var stylesave = JSON.parse(JSON.stringify(that.divsave.style.colStyle)) 
				let savecol
				for(savecol in temobj){
					stylesave.map((val)=>{
						if(val.name == savecol){
							val.style.colValue = temobj[savecol]
							val.style.value = temobj[savecol]
							return val
						}
					})
				}
				var datasave = that.datasave
				var obj = {}
				obj['opttype'] = 'insert'
				obj['data'] = stylesave
				datasave.push(obj)
				that.datasave = datasave
				console.log(that.datasave)
 				
			}else if(itemvalue == 1){
				itemvalue = 0
				let maparr = item.filter((val, index)=>{
					 return val.name == that.keyColumn
				})
				var colValue = maparr[0].style.value
				var datasave = that.datasave
				datasave.map((val,index)=>{
					val.data.map((val2, index2)=>{
						if(val2.style.value == colValue){
							val.opttype = 'delete'
							return val
						}
					})
				})
				that.datasave = datasave
				console.log(that.datasave)
				
			}
			
			item[that.selectedindex].style.value = itemvalue
			datalist[index].data = item
			that.datalist = datalist
			
			var nameColumn = that.nameColumn
			var namesColumn = that.namesColumn
			var namesValue = ''
			datalist.forEach((val)=>{
				val.data.forEach((val2)=>{
					if(val2.name === nameColumn && val.data[0].style.value === 1){
						namesValue += val2.style.colValue + ','
					}
				})
			})
			namesValue = namesValue.substring(0, (namesValue.length - 1))
			var setnames = that.setnames[0].data
			setnames.map((val)=>{
				if(val.name === namesColumn){
					val.style.value = namesValue
					val.style['ismodifyed'] = true
					return val
				}
			})
			that.setnames[0].opttype = 'update'
			that.setnames[0].data = setnames
			console.log(that.setnames)
		},
		
		btnclick(index){
			var that = this
			var btns = that.btns
			var btntype = btns[index].name
			var btntext = btns[index].text
			var todo = btns[index].btnToDo
			var productCode = uni.getStorageSync('productCode')
			var sessionId = uni.getStorageSync('sessionId')
			var projectCode = uni.getStorageSync('projectCode')
			var terminaltype = uni.getStorageSync('terminaltype')
			var dbId = uni.getStorageSync('dbId')
			var userId = uni.getStorageSync('userId')
			var userName = uni.getStorageSync('userName')
			
			var injsondate = '{"productCode":"' + productCode + '","terminalType":"' + terminaltype + '","dbId":"' + dbId + '","sessionId":"' + sessionId + '"}';
			uni.request({
				url: getApp().globalData.app_address + '?method=getDate&parse=json',
				data: injsondate,
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded'
				},
				success: function(res) {
					console.log(res)
						var datestr = res.data.data.getDate
						console.log(datestr)
						var date = datestr.substring(0,19)
						if(todo == 'save' ){
							if((JSON.stringify(that.datalist) == JSON.stringify(that.olddatalist))){
								uni.showModal({
								    title: '提示',
								    content: '没有要提交的数据',
									showCancel:false
								})
								return
							}
							
							if(that.isrequest){
								that.isrequest = false	
								var commitArr = []
								var commitobj1 = infolistutil.getcommitobj(that.divsave, that.datasave, that.olddatasave)
								var commitobj2 = infolistutil.getcommitobj(that.divsetname, that.setnames, that.oldsetnames)
								commitArr.push(commitobj1)
								commitArr.push(commitobj2)
								
								
								var pageName = that.pageName
								var templetName = that.templetName
								var modid = that.modid
								var menuid = that.menuid
								var injson = '{"productCode":"' + productCode + '","terminalType":"' + terminaltype + '","projectCode":"' +
									projectCode + '","dbId":"' + dbId + '","templetName":"' + templetName + '","pageName":"' + pageName +
									'","menuId":"'+menuid+'","modId":"' + modid + '","sessionId":"' + sessionId + '","userId":"' + userId +
									'","userName":"' + userName + '","btnName":"' + btntype + '","btnText":"' + btntext + '","commitArr":' + JSON.stringify(commitArr) + '}';
								console.log(injson)
								uni.showLoading({title: '加载中'})
								uni.request({
									url: getApp().globalData.app_address + '?method=saas_PageCommitData&parse=json',
									data: injson,
									method: 'POST',
									header: {'content-type': 'application/x-www-form-urlencoded'},
									success: function(res) {
										var result = res.data
										uni.hideLoading()
										console.log(result)
										if(result.rtn == 1){
											uni.showToast({title: '操作成功!',position:'bottom',icon:'none',duration: 1000 })
											setTimeout(function() {
												let pages = getCurrentPages();
												let beforePage = pages[pages.length  -2];
												beforePage.$vm.reload(JSON.stringify(that.setnames[0].data),that.setnames[0].opttype)
												uni.navigateBack({delta: 1})
											}, 1000);
										}
									},
								})
								
							}
						}
					}
				})
		},
		
	}
}
</script>

<style>
	.main-view{width: 100vw;height: 100vh;background-color: #f0f0f0;}
	.content-view{width: 100vw;height: 100vh;position:relative;}
	.error-view{display: flex;color: #aaa;justify-content: center;flex-direction: column;align-items: center;}
	.bottom-wrapper{background-color: #fff; height: 40px; width: 100vw;display: flex;flex-direction: row;justify-content: space-between;position: absolute;bottom: 0;align-items: center;z-index:200}
</style>